﻿using SharpZip.Net;
using System.IO;
using System.Windows;

namespace SharpZip.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private AesEncryptorKey key = new AesEncryptorKey("tAo0rVAOgcBpY85ioDGNIviVw1q9MtEgj1YS7cC78EQ =", "6YJ58PB4HOWxrlbxuUv7Dw ==");

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SourceDirectoryTextBox.Text))
            {
                AppendMessage("请输入文件夹！");
                return;
            }

            if (string.IsNullOrWhiteSpace(TargetZipFileTextBox.Text))
            {
                AppendMessage("请输入输出文件！");
                return;
            }

            var sourceDirectory = SourceDirectoryTextBox.Text.Trim();
            var targetZipFile = TargetZipFileTextBox.Text.Trim();

            try
            {
                AesTextZipFile.CreateFromDirectory(sourceDirectory, targetZipFile, key, GetIngoreDirectories());
                AppendMessage("压缩完成！");
            }
            catch (Exception ex)
            {
                AppendMessage(ex.Message);
            }
        }

        private void SourceDirectoryTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SourceDirectoryTextBox.Text))
            {
                return;
            }

            if (IsDirectoryPathValid(SourceDirectoryTextBox.Text))
            {
                var targetFile = SourceDirectoryTextBox.Text.Trim() + ".txt";
                TargetZipFileTextBox.Text = targetFile;
            }
        }

        private string[] GetIngoreDirectories()
        {
            var text = IgnoreDirectiresTextBox.Text.Trim();

            if (string.IsNullOrWhiteSpace(text))
            {
                return [];
            }

            TextReader reader = new StringReader(text);
            var lines = new List<string>();
            var line = reader.ReadLine();

            while (line != null)
            {
                lines.Add(line);
                line = reader.ReadLine();
            }

            return lines.Where(item => !string.IsNullOrWhiteSpace(item)).Distinct().ToArray();
        }

        // 简单的目录路径格式验证方法
        static bool IsDirectoryPathValid(string path)
        {
            // 注意：这个验证非常基础，并不涵盖所有可能的无效路径情况。
            // 对于更严格的验证，你可能需要使用正则表达式或更复杂的逻辑。
            char[] invalidChars = Path.GetInvalidPathChars();
            foreach (char c in path)
            {
                if (invalidChars.Any(charItem => charItem == c))
                {
                    return false;
                }
            }

            // 额外的检查：路径不应该只是根目录的一个点（例如，C:\）后跟无效字符
            // 这里还可以添加更多检查，比如路径不应该包含`..`等

            // 注意：这个方法不检查路径是否过长（超过MAX_PATH限制），也不检查文件系统权限。

            return true;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TargetZipFileTextBox.Text))
            {
                AppendMessage("请输入文件！");
                return;
            }

            var targetZipFile = TargetZipFileTextBox.Text.Trim();

            if (!File.Exists(targetZipFile))
            {
                AppendMessage("文件不存在！");
                return;
            }

            var text = File.ReadAllText(targetZipFile);

            Clipboard.SetText(text);
            AppendMessage("内容已复制到剪切板！");

        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var sourceZipFile = SourceZipFileTextBox.Text.Trim();
            var targetDir = TargetDirectoryTextBox.Text.Trim();

            if (string.IsNullOrWhiteSpace(sourceZipFile))
            {
                AppendMessage("请输入需要解压的文件！");
                return;
            }

            try
            {
                AesTextZipFile.ExtractToDirectory(sourceZipFile, targetDir, key);
                AppendMessage("解压完成！");

            }
            catch (Exception ex)
            {
                AppendMessage(ex.Message);
            }
        }

        private void SourceZipFileTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SourceZipFileTextBox.Text))
            {
                return;
            }

            if (IsDirectoryPathValid(SourceZipFileTextBox.Text))
            {
                var sourceZipFile = SourceZipFileTextBox.Text.Trim();

                if (Path.Exists(sourceZipFile))
                {
                    var fileInfo = new FileInfo(sourceZipFile);
                    var targetDir = Path.Combine(fileInfo.Directory.FullName, Path.GetFileNameWithoutExtension(fileInfo.Name));
                    this.TargetDirectoryTextBox.Text = targetDir;
                }
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Button_Click(sender, e);
            Button_Click_1(sender, e);
        }

        private void AppendMessage(string message)
        {
            MessageTextBox.Text = message + "\n" + MessageTextBox.Text;
        }
    }
}